<template>
  <div class="menu-container">
    <!-- 错误边界 -->
    <div v-if="hasError" style="color: red; padding: 20px; background: #fff3cd; border: 1px solid #ffeaa7;">
      <h3>页面加载出错</h3>
      <p>{{ errorMessage }}</p>
      <el-button @click="retryLoad" type="primary">重试</el-button>
    </div>
    
    <!-- 加载状态 -->
    <div v-else-if="isLoading" style="text-align: center; padding: 50px;">
      <el-icon class="is-loading" style="font-size: 24px; color: #409eff;"><Loading /></el-icon>
      <p>正在加载页面...</p>
    </div>
    
    <!-- 主要内容 -->
    <el-container v-else>
      
      <el-header class="top-header">
        <div class="logo-container">
          <span class="company-name">ERP&MES</span>
        </div>

        <div class="header-nav">
          <el-menu mode="horizontal" class="horizontal-menu" background-color="transparent" text-color="#fff" active-text-color="#fff" :ellipsis="false" :default-active="activeTopMenu">
            <el-menu-item 
              v-for="menu in topMenus" 
              :key="menu.index" 
              :index="menu.index"
              @click="handleTopMenuClick(menu)"
            >
              {{ menu.label }}
            </el-menu-item>
          </el-menu>
        </div>

        <div class="header-right">
          <el-button link class="header-icon">
            <el-icon><Bell /></el-icon>
          </el-button>
          
          <!-- 用户下拉菜单 -->
          <el-dropdown @command="handleUserCommand" trigger="click">
            <div class="user-dropdown-trigger">
              <el-icon><User /></el-icon>
              <span>{{ store.userInfo.Nickname || store.userInfo.UserName || 'Admin' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><Document /></el-icon>
                  <span>基本资料</span>
                </el-dropdown-item>
                <el-dropdown-item command="password">
                  <el-icon><Lock /></el-icon>
                  <span>修改密码</span>
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  <span>退出系统</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <el-button link class="header-icon">
            <el-icon><Setting /></el-icon>
          </el-button>
        </div>
      </el-header>
      <el-container class="main-content">
        <!-- Left Sidebar -->
        <el-aside width="250px" class="sidebar">
          <el-menu
              :default-active="activeMainMenu"
              class="el-menu-vertical"
              background-color="#2c3e50"
              text-color="#ecf0f1"
              active-text-color="#3498db"
              unique-opened
          >
            <!-- 动态渲染左侧菜单项 -->
            <template v-for="menuItem in currentLeftMenus" :key="menuItem.value || menuItem.id">
              <!-- 如果有子菜单，使用子菜单组件 -->
              <el-sub-menu v-if="menuItem.children && menuItem.children.length > 0" :index="menuItem.value?.toString() || menuItem.id?.toString()">
                <template #title>
                  <el-icon v-if="menuItem.icon"><component :is="menuItem.icon" /></el-icon>
                  <span>{{ menuItem.label }}</span>
                </template>
                <el-menu-item 
                  v-for="child in menuItem.children" 
                  :key="child.value || child.id"
                  :index="child.value?.toString() || child.id?.toString()"
                  @click="handleLeftMenuClick(child)"
                >
                  <el-icon v-if="child.icon"><component :is="child.icon" /></el-icon>
                  <span>{{ child.label }}</span>
                </el-menu-item>
              </el-sub-menu>
              <!-- 如果没有子菜单，使用普通菜单项 -->
              <el-menu-item 
                v-else 
                :index="menuItem.value?.toString() || menuItem.id?.toString()"
                @click="handleLeftMenuClick(menuItem)"
              >
                <el-icon v-if="menuItem.icon"><component :is="menuItem.icon" /></el-icon>
                <span>{{ menuItem.label }}</span>
              </el-menu-item>
            </template>
          </el-menu>
        </el-aside>
        
        <el-main class="content-section">
          <!-- 路由视图 -->
          <div class="content-container" v-if="$route.path !== '/' && $route.path !== '/Main'">
            <router-view />
          </div>
          
          <!-- 工作台内容 -->
          <div class="workbench-content" v-if="$route.path === '/' || $route.path === '/Main'">
            <div class="page-title">工作台</div>
            
            <!-- 核心指标区域 -->
            <div class="core-indicators">
              <div class="indicators-header">
                <h3>核心指标</h3>
                <span class="date">{{ currentDate }}</span>
              </div>
              <div class="indicators-grid">
                <div class="indicator-item">
                  <div class="indicator-icon">¥</div>
                  <div class="indicator-content">
                    <div class="indicator-label">今日销售收入(元)</div>
                    <div class="indicator-value">5000.00</div>
                  </div>
                </div>
                <div class="indicator-item">
                  <div class="indicator-icon">📄</div>
                  <div class="indicator-content">
                    <div class="indicator-label">今日销售订单量(笔)</div>
                    <div class="indicator-value">100</div>
                  </div>
                </div>
                <div class="indicator-item">
                  <div class="indicator-icon">💰</div>
                  <div class="indicator-content">
                    <div class="indicator-label">今日回款(元)</div>
                    <div class="indicator-value">5000.00</div>
                  </div>
                </div>
                <div class="indicator-item">
                  <div class="indicator-icon">🛒</div>
                  <div class="indicator-content">
                    <div class="indicator-label">今日采购支出(元)</div>
                    <div class="indicator-value">5000.00</div>
                  </div>
                </div>
                <div class="indicator-item">
                  <div class="indicator-icon">📋</div>
                  <div class="indicator-content">
                    <div class="indicator-label">今日采购订单(笔)</div>
                    <div class="indicator-value">5000.00</div>
                  </div>
                </div>
                <div class="indicator-item">
                  <div class="indicator-icon">💳</div>
                  <div class="indicator-content">
                    <div class="indicator-label">今日已付款</div>
                    <div class="indicator-value">5000.00</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 统计图表区域 -->
            <div class="statistics-section">
              <div class="statistics-tabs">
                <el-tabs v-model="activeStatisticsTab" class="statistics-tabs-content">
                  <el-tab-pane label="销售统计" name="sales">
                    <div class="chart-container">
                      <div class="chart-header">
                        <div class="chart-controls">
                          <el-button size="small" :type="timeRange === 'week' ? 'primary' : 'default'" @click="changeTimeRange('week')">最近1周</el-button>
                          <el-button size="small" :type="timeRange === 'month' ? 'primary' : 'default'" @click="changeTimeRange('month')">最近30天</el-button>
                          <el-button size="small" :type="timeRange === 'year' ? 'primary' : 'default'" @click="changeTimeRange('year')">最近1年</el-button>
                        </div>
                      </div>
                      <div class="chart-wrapper">
                        <div ref="salesChartRef" class="chart-container"></div>
                      </div>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="采购统计" name="procurement">
                    <div class="chart-wrapper">
                      <div ref="procurementChartRef" class="chart-container"></div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
            
            <!-- 待审批单据区域 -->
            <div class="approval-section">
              <div class="section-header">
                <h3>待审批单据</h3>
              </div>
              <div class="approval-grid">
                <div class="approval-item">
                  <div class="approval-count">0</div>
                  <div class="approval-label">采购订单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">5</div>
                  <div class="approval-label">销售订单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">0</div>
                  <div class="approval-label">入库单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">3</div>
                  <div class="approval-label">出库单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">2</div>
                  <div class="approval-label">到票单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">1</div>
                  <div class="approval-label">支出单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">6</div>
                  <div class="approval-label">开票单</div>
                </div>
                <div class="approval-item">
                  <div class="approval-count">0</div>
                  <div class="approval-label">请购单</div>
                </div>
              </div>
            </div>
            
            <!-- 通知公告和提醒任务区域 -->
            <div class="bottom-section">
              <div class="notification-section">
                <div class="section-header">
                  <h3>通知公告</h3>
                </div>
                <div class="notification-list">
                  <div class="notification-item">
                    <span class="notification-content">春节放假通知</span>
                    <span class="notification-time">2025-08-14 19:40:33</span>
                  </div>
                  <div class="notification-item">
                    <span class="notification-content">五一放假通知</span>
                    <span class="notification-time">2025-08-14 19:40:33</span>
                  </div>
                  <div class="notification-item">
                    <span class="notification-content">端午节放假通知</span>
                    <span class="notification-time">2025-08-14 19:40:33</span>
                  </div>
                  <div class="notification-item">
                    <span class="notification-content">国庆放假通知</span>
                    <span class="notification-time">2025-08-14 19:40:33</span>
                  </div>
                </div>
              </div>
              
              <div class="reminder-section">
                <div class="section-header">
                  <h3>提醒任务</h3>
                </div>
                <el-tabs v-model="activeReminderTab" class="reminder-tabs">
                  <el-tab-pane label="订单交付提醒" name="delivery">
                    <div class="reminder-table">
                      <div class="reminder-item">
                        <span class="reminder-number">XSDH2023512698</span>
                        <span class="reminder-subject">新产品销售0234</span>
                        <span class="reminder-type">销售订单</span>
                        <span class="reminder-status">待交付</span>
                        <span class="reminder-date">2027-06-08</span>
                        <span class="reminder-action">查看</span>
                      </div>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="工单提醒" name="workorder">
                    <div class="reminder-table">
                      <p>暂无工单提醒</p>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="工序提醒" name="process">
                    <div class="reminder-table">
                      <p>暂无工序提醒</p>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="即将到期物品" name="expiring">
                    <div class="reminder-table">
                      <p>暂无即将到期物品</p>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="已到期物品" name="expired">
                    <div class="reminder-table">
                      <p>暂无已到期物品</p>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
          
          <!-- 当没有激活标签页时显示空白 -->
          <div class="empty-content" v-else></div>
        </el-main>
        
        <!-- Right Sidebar -->
        <el-aside width="60px" class="right-sidebar">
          <div class="right-toolbar">
            <div class="toolbar-item">
              <el-icon><Search /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><Star /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><Folder /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><User /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><Box /></el-icon>
            </div>
            <div class="toolbar-item">
              <el-icon><Document /></el-icon>
              <span class="toolbar-text">译</span>
            </div>
            <div class="toolbar-item expand-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </el-aside>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
import { getMenu } from '@/Https/server';
import * as echarts from 'echarts';
const store = useCounterStore();
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
const router = useRouter();
const route = useRoute();
import { onMounted, onUnmounted, ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// 页面状态
const isLoading = ref(true);
const hasError = ref(false);
const errorMessage = ref('');

// 菜单状态
const activeMainMenu = ref('');
const activeTopMenu = ref('workbench'); // 默认选中"工作台"菜单
const activeStatisticsTab = ref('sales');
const timeRange = ref('year'); // 默认显示年度数据
const activeReminderTab = ref('delivery');

// 监听统计标签页变化
watch(activeStatisticsTab, (newTab) => {
  nextTick(() => {
    // 延迟处理标签页变化，确保图表正确渲染
    setTimeout(() => {
      if (newTab === 'sales' && salesChart) {
        salesChart.resize();
      } else if (newTab === 'procurement' && procurementChart) {
        procurementChart.resize();
      }
    }, 100);
  });
});

// 处理标签页点击事件
const handleTabClick = (tab: any) => {
  console.log('标签页被点击:', tab);
  // 可以在这里添加标签页点击的逻辑
};

// 图表相关
const salesChartRef = ref<HTMLElement>();
const procurementChartRef = ref<HTMLElement>();
let salesChart: echarts.ECharts | null = null;
let procurementChart: echarts.ECharts | null = null;




// 顶部导航菜单数据 - 使用store中的菜单数据
const topMenus = computed(() => {
  // 将store中的菜单数据转换为顶部导航需要的格式
  return store.menus.map((item: any) => ({
    index: item.value?.toString() || item.id?.toString() || '',
    label: item.label || item.title || '',
    url: item.url || item.path || ''
  }));
});

// 当前左侧菜单数据 - 根据选中的顶部菜单动态获取子菜单
const currentLeftMenus = computed(() => {
  // 根据当前选中的顶部菜单，获取对应的子菜单
  const selectedTopMenu = store.menus.find((item: any) => 
    (item.value?.toString() || item.id?.toString()) === activeTopMenu.value
  );
  
  // 如果找到了选中的顶部菜单且有子菜单，返回子菜单
  if (selectedTopMenu && selectedTopMenu.children && selectedTopMenu.children.length > 0) {
    return selectedTopMenu.children;
  }
  
  // 如果没有找到或没有子菜单，返回空数组
  return [];
});

// 获取当前日期
const currentDate = ref(new Date().toISOString().split('T')[0]);

// 根据菜单项获取对应的图标
const getIconForMenu = (item: any) => {
  // 根据菜单名称或类型返回合适的图标
  const iconMap: Record<string, string> = {
    '溯源管理': 'Location',
    '溯源产品管理': 'Document',
    '用户管理': 'User',
    '角色管理': 'UserFilled',
    '权限管理': 'Setting',
  };
  
  return iconMap[item.label] || 'Document';
};

// 获取主菜单图标
const getIconForMainMenu = (item: any) => {
  const iconMap: Record<string, string> = {
    'RBAC管理': 'Setting',
    '溯源管理': 'Location',
  };
  
  return iconMap[item.label] || 'Menu';
};

// 归一化并修复菜单路由路径
const normalizeMenuRoutePath = (menu: any): string => {
  let p = menu.url || menu.path || menu.name || ''
  // 修复 "//"、"/" 或空路径
  if (!p || p === '/' || p === '//' || p === '#') {
    const label = (menu.label || menu.title || '').toString()
    const mapByLabel: Record<string, string> = {
      '仓库管理': '/WarehouseManagement',
      '入库管理': '/InboundList',
      '供应商管理': '/SupplierManagement',
      '客户管理': '/CustomerManagement',
      '采购订单管理': '/PurchaseOrderList',
      '到货检验管理': '/IncomingInspectionList',
      '销售订单管理': '/SalesOrderList'
    }
    p = mapByLabel[label] || ''
    // 关键字兜底映射
    if (!p) {
      if (/入库/.test(label)) p = '/InboundList'
      else if (/仓库/.test(label)) p = '/WarehouseManagement'
      else if (/供应商/.test(label)) p = '/SupplierManagement'
      else if (/客户/.test(label)) p = '/CustomerManagement'
      else if (/采购/.test(label)) p = '/PurchaseOrderList'
      else if (/检验/.test(label)) p = '/IncomingInspectionList'
      else if (/销售/.test(label)) p = '/SalesOrderList'
    }
  }
  if (!p) return ''
  // 去重前缀斜杠并确保以单个斜杠开头
  p = '/' + String(p).replace(/^\/+/, '')
  return p
}

const routeExists = (path: string) => router.getRoutes().some(r => r.path === path)

const retryLoad = async () => {
  hasError.value = false;
  errorMessage.value = '';
  isLoading.value = true;
  await initializeComponent();
};

const initializeComponent = async () => {
  try {
    console.log('Menu组件开始挂载...');
    
    // 检查用户是否已登录
    if (!store.userInfo.Nickname || !store.userInfo.roleId) {
      console.log('用户未登录，跳转到登录页');
      router.push('/');
      return;
    }
    
    console.log('用户已登录:', store.userInfo);
    
    // 加载菜单数据
    console.log('开始加载菜单数据...');
    await store.getMenus();
    console.log('菜单数据加载完成:', store.menus);

    // 首次根据当前路由同步标签页
    syncTabWithCurrentRoute(route.path)
    
    // 初始化图表
    nextTick(() => {
      initCharts();
      
      // 延迟再次初始化，确保图表正确渲染
      setTimeout(() => {
        initCharts();
      }, 500);
    });
    
    // 监听窗口大小变化，图表自适应
    window.addEventListener('resize', handleResize);
    
    // 延迟添加窗口大小变化监听器，确保图表正确渲染
    setTimeout(() => {
      window.addEventListener('resize', handleResize);
    }, 1000);
    
    console.log('Menu组件挂载完成');
    isLoading.value = false;
  } catch (error) {
    console.error('Menu组件挂载失败:', error);
    hasError.value = true;
    errorMessage.value = error instanceof Error ? error.message : '未知错误';
    isLoading.value = false;
  }
};

// 监听路由变化，同步到标签页与激活状态
const syncTabWithCurrentRoute = (path: string) => {
  if (!path || path === '/' || path === '/Main') return

  // 查找是否已有对应标签
  const exists = store.tabs.find(t => t.name === path)
  if (!exists) {
    // 在菜单树中查找匹配项以取标题
    let label = ''
    const dfs = (nodes: any[]): boolean => {
      if (!nodes) return false
      for (const n of nodes) {
        const p = normalizeMenuRoutePath(n)
        if (p === path) {
          label = n.label || n.title || ''
          return true
        }
        if (n.children && dfs(n.children)) return true
      }
      return false
    }
    dfs(store.menus)
    if (!label) {
      label = (router.currentRoute.value.meta?.title as string) || path.replace(/^\//, '')
    }

    store.addTab({ title: label, label, url: path, name: path, closable: true })
  }
  store.activeTab = path
}

watch(() => route.path, (p) => {
  syncTabWithCurrentRoute(p)
})

onMounted(() => {
  initializeComponent();
});

// 组件卸载时清理资源
onUnmounted(() => {
  // 移除事件监听器
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  if (salesChart) {
    salesChart.dispose();
    salesChart = null;
  }
  if (procurementChart) {
    procurementChart.dispose();
    procurementChart = null;
  }
});

//退出功能
const out = () => {
  // 清除用户信息
  store.userInfo.Nickname = '';
  store.userInfo.roleId = '';
  store.userInfo.roleName = '';
  
  // 清除本地存储中的token
  localStorage.removeItem('token');
  localStorage.removeItem('refreshToken');
  
  // 清除Pinia持久化存储
  localStorage.removeItem('counter');
  
  // 跳转到登录页
  router.push({path:"/"});
}

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  Lock,
  User,
  UserFilled,
  SwitchButton,
  Lightning,
  Search,
  Bell,
  Star,
  Tools,
  Clock,
  Folder,
  ChatDotRound,
  Box,
  ArrowRight,
  ArrowDown,
  Loading
} from '@element-plus/icons-vue'

//控制菜单是否展开
const isCollapse = ref(false)



// 处理用户下拉菜单命令
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      // 处理基本资料
      console.log('查看基本资料');
      break;
    case 'password':
      // 处理修改密码
      console.log('修改密码');
      break;
    case 'logout':
      // 处理退出系统
      out();
      break;
    default:
      break;
  }
};

// 处理顶部菜单点击
const handleTopMenuClick = (menu: any) => {
  activeTopMenu.value = menu.index;
  console.log('点击了顶部菜单:', menu.label);
  // 重置左侧菜单的选中状态
  activeMainMenu.value = '';
  // 这里可以添加具体的菜单处理逻辑
  // 比如跳转页面、显示对应内容等
};

// 处理左侧菜单点击
const handleLeftMenuClick = (menu: any) => {
  activeMainMenu.value = menu.value?.toString() || menu.id?.toString() || '';
  console.log('点击了左侧菜单:', menu.label);
  
  // 执行路由跳转
  const routePath = menu.url || menu.path || '';
  if (routePath) {
    router.push(routePath);
  }
};

// 图表相关方法
const initCharts = () => {
  if (salesChartRef.value) {
    salesChart = echarts.init(salesChartRef.value);
    updateSalesChart();
  }
  
  if (procurementChartRef.value) {
    procurementChart = echarts.init(procurementChartRef.value);
    updateProcurementChart();
  }
  
  // 确保图表正确渲染
  nextTick(() => {
    if (salesChart) {
      salesChart.resize();
    }
    if (procurementChart) {
      procurementChart.resize();
    }
  });
};

const updateSalesChart = () => {
  if (!salesChart) return;
  
  const option = getSalesChartOption();
  salesChart.setOption(option, true);
  
  // 确保图表正确渲染
  nextTick(() => {
    if (salesChart) {
      salesChart.resize();
    }
  });
};

const updateProcurementChart = () => {
  if (!procurementChart) return;
  
  const option = getProcurementChartOption();
  procurementChart.setOption(option, true);
  
  // 确保图表正确渲染
  nextTick(() => {
    if (procurementChart) {
      procurementChart.resize();
    }
  });
};

const getSalesChartOption = () => {
  const { xAxisData, orderAmountData, orderCountData } = getChartData();
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['订单额', '订单数'],
      top: 10,
      left: 'center'
    },
    grid: {
      left: '8%',
      right: '8%',
      bottom: '8%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisPointer: {
          type: 'none'
        },
        axisLabel: {
          color: '#333',
          fontSize: 12
        },
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc' }
        },
        splitLine: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '单位(元)',
        nameLocation: 'end',
        nameTextStyle: {
          padding: [0, 0, 0, 30]
        },
        min: 0,
        max: 600,
        interval: 100,
        axisLabel: {
          formatter: '{value}',
          color: '#333'
        },
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc' }
        },
        splitLine: {
          show: true,
          lineStyle: { color: '#eee' }
        }
      },
      {
        type: 'value',
        name: '单位(笔)',
        nameLocation: 'end',
        nameTextStyle: {
          padding: [0, 0, 0, -30]
        },
        min: 0,
        max: 60,
        interval: 10,
        axisLabel: {
          formatter: '{value}',
          color: '#333'
        },
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc' }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '订单额',
        type: 'bar',
        barWidth: '50%',
        itemStyle: { color: '#409EFF' },
        data: orderAmountData,
        z: 1
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: { color: '#9370DB' },
        lineStyle: { width: 2 },
        data: orderCountData,
        z: 2
      }
    ]
  };
};

const getProcurementChartOption = () => {
  const { xAxisData, orderAmountData, orderCountData } = getChartData();
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['采购额', '采购单数'],
      top: 10,
      left: 'center'
    },
    grid: {
      left: '8%',
      right: '8%',
      bottom: '8%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData,
        axisPointer: {
          type: 'none'
        },
        axisLabel: {
          color: '#333',
          fontSize: 12
        },
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc' }
        },
        splitLine: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '单位(元)',
        nameLocation: 'end',
        nameTextStyle: {
          padding: [0, 0, 0, 30]
        },
        min: 0,
        max: 600,
        interval: 100,
        axisLabel: {
          formatter: '{value}',
          color: '#333'
        },
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc' }
        },
        splitLine: {
          show: true,
          lineStyle: { color: '#eee' }
        }
      },
      {
        type: 'value',
        name: '单位(笔)',
        nameLocation: 'end',
        nameTextStyle: {
          padding: [0, 0, 0, -30]
        },
        min: 0,
        max: 60,
        interval: 10,
        axisLabel: {
          formatter: '{value}',
          color: '#333'
        },
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc' }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '采购额',
        type: 'bar',
        barWidth: '50%',
        itemStyle: { color: '#e74c3c' },
        data: orderAmountData.map(val => val * 0.8),
        z: 1
      },
      {
        name: '采购单数',
        type: 'line',
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: { color: '#f39c12' },
        lineStyle: { width: 2 },
        data: orderCountData.map(val => val * 0.9),
        z: 2
      }
    ]
  };
};

const getChartData = () => {
  let xAxisData: string[] = [];
  let orderAmountData: number[] = [];
  let orderCountData: number[] = [];
  
  switch (timeRange.value) {
    case 'week':
      xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      orderAmountData = [320, 450, 280, 520, 380, 420, 480];
      orderCountData = [32, 45, 28, 52, 38, 42, 48];
      break;
    case 'month':
      xAxisData = ['第1周', '第2周', '第3周', '第4周'];
      orderAmountData = [1200, 1350, 980, 1520];
      orderCountData = [120, 135, 98, 152];
      break;
    case 'year':
    default:
      xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
      // 根据图一和图二的实际数据
      orderAmountData = [100, 570, 370, 290, 130, 320, 170, 490, 200, 70, 500, 530];
      orderCountData = [15, 20, 25, 55, 15, 30, 53, 40, 28, 15, 55, 28];
      break;
  }
  
  return { xAxisData, orderAmountData, orderCountData };
};

const changeTimeRange = (range: string) => {
  timeRange.value = range;
  
  // 延迟更新图表，确保DOM更新完成
  nextTick(() => {
    updateSalesChart();
    updateProcurementChart();
  });
};

const handleResize = () => {
  // 延迟处理窗口大小变化，确保图表正确渲染
  setTimeout(() => {
    if (salesChart) {
      salesChart.resize();
    }
    if (procurementChart) {
      procurementChart.resize();
    }
  }, 100);
};

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 延迟清理图表，确保完全清理
  setTimeout(() => {
    if (salesChart) {
      salesChart.dispose();
      salesChart = null;
    }
    if (procurementChart) {
      procurementChart.dispose();
      procurementChart = null;
    }
  }, 100);
});
</script>

<style scoped>
/* ==================== 整体布局 ==================== */
.menu-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow-x: hidden; /* 防止整个页面出现水平滚动条 */
  position: relative;
}

/* ==================== 顶部导航栏 ==================== */
.top-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  position: relative;
  z-index: 1000;
  width: 100%; /* 使用100%宽度而不是固定最小宽度 */
  box-sizing: border-box; /* 确保padding不会增加总宽度 */
  overflow: hidden;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.company-name {
  color: white;
  font-size: 20px;
  font-weight: 600;
  position: relative;
  z-index: 10;
}

.header-nav {
  flex: 1;
  display: flex;
  justify-content: center;
  min-width: 0;
  overflow: hidden;
}

.horizontal-menu {
  border-bottom: none;
  background-color: transparent !important;
  flex-wrap: nowrap;
  overflow: hidden;
}

.horizontal-menu :deep(.el-menu-item) {
  color: #fff !important;
  border-bottom: none;
  height: 60px;
  line-height: 60px;
  font-size: 14px;
  font-weight: 500;
  margin: 0 5px;
  border-radius: 4px;
  white-space: nowrap;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
}

.horizontal-menu :deep(.el-menu-item:hover) {
  background-color: rgba(255,255,255,0.1) !important;
  color: #fff !important;
  position: relative;
  z-index: 11;
}

.horizontal-menu :deep(.el-menu-item.is-active) {
  background-color: rgba(255,255,255,0.2) !important;
  color: #fff !important;
  border-bottom: 2px solid #fff;
  position: relative;
  z-index: 11;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-shrink: 0;
}



.header-icon {
  color: #fff;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.header-icon:hover {
  background-color: rgba(255,255,255,0.1);
  transform: translateY(-1px);
  position: relative;
  z-index: 11;
}

.header-icon .el-icon {
  font-size: 18px;
  position: relative;
  z-index: 10;
}

.header-icon span {
  font-size: 14px;
  font-weight: 500;
  position: relative;
  z-index: 10;
}

/* 用户下拉菜单样式 */
.user-dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #fff;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: transparent;
}

.user-dropdown-trigger:hover {
  background-color: rgba(255,255,255,0.1);
  transform: translateY(-1px);
  position: relative;
  z-index: 11;
}

.user-dropdown-trigger .el-icon {
  font-size: 18px;
  position: relative;
  z-index: 10;
}

.user-dropdown-trigger span {
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  position: relative;
  z-index: 10;
}

/* 下拉菜单样式 */
:deep(.el-dropdown-menu) {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  border: 1px solid #e8e8e8;
  position: relative;
  z-index: 1001;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1002;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: #f5f7ff;
  color: #409eff;
  position: relative;
  z-index: 1003;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 16px;
  margin-right: 0;
  position: relative;
  z-index: 1002;
}

/* ==================== 主内容区域 ==================== */
.main-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

/* ==================== 侧边栏 ==================== */
.sidebar {
  background-color: #2c3e50;
  height: calc(100vh - 60px);
  overflow: hidden;
  border-right: 1px solid #34495e;
  position: relative;
}

.el-menu-vertical {
  height: 100%;
  overflow-y: auto;
  border-right: none;
  background-color: #2c3e50 !important;
  position: relative;
}

.el-menu-vertical :deep(.el-menu-item) {
  background-color: #2c3e50 !important;
  color: #ecf0f1 !important;
  border-bottom: 1px solid #34495e;
  height: 50px;
  line-height: 50px;
  margin: 0;
  position: relative;
  z-index: 2;
}

.el-menu-vertical :deep(.el-menu-item:hover) {
  background-color: #34495e !important;
  color: #fff !important;
  position: relative;
  z-index: 3;
}

.el-menu-vertical :deep(.el-menu-item.is-active) {
  background-color: #34495e !important;
  color: #fff !important;
  border-left: 4px solid #3498db;
  position: relative;
  z-index: 3;
}

.active-menu-item {
  background-color: #34495e !important;
  color: #fff !important;
  border-left: 4px solid #3498db;
  position: relative;
  z-index: 3;
}

.el-menu-vertical :deep(.el-icon) {
  margin-right: 10px;
  font-size: 16px;
  position: relative;
  z-index: 2;
}

/* ==================== 内容区域 ==================== */
.content-section {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px); /* 固定高度 */
  overflow: hidden; /* 禁止滚动 */
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  position: relative;
}

/* ==================== 内容容器 ==================== */
.content-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow: hidden; /* 禁止滚动 */
  border: 1px solid #e8e8e8;
  position: relative;
  height: 100%; /* 占满父容器高度 */
  display: flex;
  flex-direction: column;
}

/* ==================== 工作台内容 ==================== */
.workbench-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  overflow: hidden; /* 禁止滚动 */
  border: 1px solid #e8e8e8;
  box-sizing: border-box;
  position: relative;
  height: 100%; /* 占满父容器高度 */
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;
  z-index: 10;
}

/* ==================== 核心指标 ==================== */
.core-indicators {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  position: relative;
}

.indicators-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
  z-index: 10;
}

.indicators-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.date {
  color: #7f8c8d;
  font-size: 14px;
  position: relative;
  z-index: 2;
}

.indicators-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
  position: relative;
}

.indicator-item {
  display: flex;
  align-items: center;
  gap: 15px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.indicator-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(135deg, #1890ff, #096dd9);
}

.indicator-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  border-color: #1890ff;
  position: relative;
  z-index: 3;
}

.indicator-icon {
  font-size: 24px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  border-radius: 8px;
  color: #1976d2;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.2);
  flex-shrink: 0;
  position: relative;
  z-index: 2;
}

.indicator-content {
  flex: 1;
  position: relative;
  z-index: 2;
}

.indicator-label {
  color: #7f8c8d;
  font-size: 12px;
  margin-bottom: 5px;
  position: relative;
  z-index: 2;
}

.indicator-value {
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
  position: relative;
  z-index: 2;
}

/* ==================== 统计图表 ==================== */
.statistics-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  margin-bottom: 20px;
  overflow: hidden;
}

/* ==================== 待审批单据 ==================== */
.approval-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  margin-bottom: 20px;
  position: relative;
}

.section-header h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  position: relative;
  z-index: 10;
}

.approval-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 15px;
  position: relative;
}

.approval-item {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.approval-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  position: relative;
  z-index: 3;
}

.approval-count {
  font-size: 24px;
  font-weight: 700;
  color: #e74c3c;
  margin-bottom: 8px;
  position: relative;
  z-index: 2;
}

.approval-label {
  font-size: 14px;
  color: #7f8c8d;
  position: relative;
  z-index: 2;
}

/* ==================== 底部区域 ==================== */
.bottom-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 20px;
  position: relative;
}

.notification-section,
.reminder-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  position: relative;
}

.notification-list {
  max-height: 200px;
  overflow-y: auto;
  position: relative;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e8e8e8;
  position: relative;
  z-index: 1;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-content {
  color: #2c3e50;
  font-size: 14px;
  position: relative;
  z-index: 2;
}

.notification-time {
  color: #7f8c8d;
  font-size: 12px;
  position: relative;
  z-index: 2;
}

.reminder-tabs {
  margin-top: 15px;
  position: relative;
  z-index: 10;
}

.reminder-table {
  margin-top: 15px;
  position: relative;
}

.reminder-item {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 80px;
  gap: 10px;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  font-size: 12px;
  position: relative;
  z-index: 1;
}

.reminder-number,
.reminder-subject,
.reminder-type,
.reminder-status,
.reminder-date {
  color: #2c3e50;
  position: relative;
  z-index: 2;
}

.reminder-action {
  color: #1890ff;
  cursor: pointer;
  text-decoration: underline;
  position: relative;
  z-index: 2;
}

.statistics-tabs-content :deep(.el-tabs__header) {
  margin-bottom: 20px;
  position: relative;
  z-index: 10;
  overflow: hidden;
}

.statistics-tabs {
  position: relative;
  z-index: 10;
  overflow: hidden;
}

.chart-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 1px solid #e8e8e8;
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.chart-wrapper {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 1px solid #e8e8e8;
  margin-top: 20px;
  z-index: 1;
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: 400px;
  overflow: hidden; /* 防止内容溢出 */
  position: relative;
  z-index: 1;
}

.chart-wrapper {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 1px solid #e8e8e8;
  margin-top: 20px;
  overflow: hidden; /* 防止内容溢出 */
  box-sizing: border-box; /* 确保padding不会增加总宽度 */
  position: relative;
  z-index: 1;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
  z-index: 10;
  overflow: hidden;
}



.chart-controls {
  display: flex;
  gap: 10px;
  position: relative;
  z-index: 10;
  overflow: hidden;
}

.chart-placeholder {
  position: relative;
  height: 300px;
  background-color: #fafafa;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  border: 1px solid #e8e8e8;
  background-image: 
    linear-gradient(90deg, transparent 98%, #e8e8e8 98%),
    linear-gradient(0deg, transparent 98%, #e8e8e8 98%);
  background-size: 14.28% 100%, 100% 16.66%;
  z-index: 1;
  overflow: hidden;
}

.chart-y-axis {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px 0;
  color: #7f8c8d;
  font-size: 12px;
  width: 40px;
  z-index: 2;
  overflow: hidden;
}

.chart-content {
  position: relative;
  flex: 1;
  margin-left: 40px;
  margin-right: 20px;
  margin-top: 20px;
  margin-bottom: 40px;
  z-index: 2;
  overflow: hidden;
}

.chart-bars {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  display: flex;
  align-items: end;
  justify-content: space-around;
  padding: 0 20px;
  z-index: 3;
  overflow: hidden;
}

.bar {
  width: 30px;
  background: linear-gradient(180deg, #1890ff, #096dd9);
  border-radius: 2px 2px 0 0;
  min-height: 20px;
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  z-index: 3;
  overflow: hidden;
}

.bar:hover {
  transform: scaleY(1.05);
  box-shadow: 0 4px 8px rgba(24, 144, 255, 0.4);
  position: relative;
  z-index: 4;
  overflow: hidden;
}

.chart-line {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  z-index: 4;
  overflow: hidden;
}

.chart-line::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #52c41a 0%, #52c41a 100%);
  clip-path: polygon(7% 40%, 21% 30%, 35% 60%, 49% 20%, 63% 50%, 77% 35%, 91% 45%);
  z-index: 4;
  overflow: hidden;
}

.line-point {
  position: relative;
  width: 8px;
  height: 8px;
  background: linear-gradient(135deg, #52c41a, #389e0d);
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 0 0 2px #52c41a, 0 2px 4px rgba(82, 196, 26, 0.3);
  transition: all 0.3s ease;
  z-index: 5;
  overflow: hidden;
}

.line-point:hover {
  transform: scale(1.2);
  box-shadow: 0 0 0 3px #52c41a, 0 4px 8px rgba(82, 196, 26, 0.4);
  position: relative;
  z-index: 6;
  overflow: hidden;
}

.chart-x-axis {
  display: flex;
  justify-content: space-around;
  padding: 0 40px 0 40px;
  color: #7f8c8d;
  font-size: 12px;
  position: relative;
  z-index: 2;
  overflow: hidden;
}

/* ==================== 标签页 ==================== */
:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
  position: relative;
  z-index: 10;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  position: relative;
  z-index: 10;
}

/* 标签内容容器 */
.tab-content-container {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  overflow: auto;
  height: calc(100% - 60px);
  position: relative;
}

/* 空白内容区域 */
.empty-content {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  height: calc(100% - 60px);
  position: relative;
}

:deep(.el-tabs__content) {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  overflow: auto;
  position: relative;
}

/* ==================== 右侧工具栏 ==================== */
.right-sidebar {
  background-color: #f5f5f5;
  border-left: 1px solid #e8e8e8;
  height: calc(100vh - 60px);
  overflow: hidden;
  position: relative;
}

.right-toolbar {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  height: 100%;
  position: relative;
}

.toolbar-item {
  width: 40px;
  height: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.toolbar-item:hover {
  background-color: #e6f7ff;
  color: #1890ff;
  position: relative;
  z-index: 3;
}

.toolbar-item .el-icon {
  font-size: 18px;
  margin-bottom: 2px;
  position: relative;
  z-index: 2;
}

.toolbar-text {
  font-size: 10px;
  color: #666;
  position: relative;
  z-index: 2;
}

.expand-arrow {
  margin-top: auto;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.expand-arrow:hover {
  background-color: #d9d9d9;
  position: relative;
  z-index: 3;
}

/* ==================== 通用样式 ==================== */
::-webkit-scrollbar {
  width: 0;
  height: 0;
  display: none;
}

/* 确保所有元素都有正确的层级关系 */
* {
  box-sizing: border-box;
}

/* 防止图表重叠 */
.chart-container,
.chart-wrapper {
  isolation: isolate;
}
</style>
